package com.chezhujie.www.core.init;

import com.chezhujie.www.controller.BaseController;
import com.chezhujie.www.core.init.mysql.EntityClass;
import com.chezhujie.www.core.init.mysql.annotation.Table;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 汤伟杰 on 2017/7/11.
 */
@Component
public class InitMybatisTable {
    protected final Logger log = LoggerFactory.getLogger(BaseController.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public void run() throws Exception {


        //创建表
        String dataName = getDataName("jdbc.properties","jdbc.url");//获取数据库名
        if(dataName==null){
            log.error("数据库名找不到");
            return;
        }else{
            System.out.println("数据库找到名为："+dataName);
        }
        Map<String, List<String>> tableColumnMap = getTableColumn(dataName);//获取当前数据库中存在的表名和表中的列属性
        String domainPackages = "com.chezhujie.www.domain";
        Resource[] resources = getResourceFile(dataName, domainPackages);//获取类集合
        String tablename = null;
        List<String> listSql = new ArrayList<String>();

        for(Resource resource:resources){
            String className = domainPackages+"."+resource.getFilename().substring(0,resource.getFilename().lastIndexOf("."));
            EntityClass entityClass = new EntityClass(className);
            tablename = entityClass.getTable().getName();
            if(StringUtils.isNotBlank(tablename)){//有注解的情况下
                tablename = entityClass.getTable().getName().toLowerCase();
                if(tableColumnMap.get(tablename)==null){
                    System.err.println("解析："+tablename+",但数据库中找到："+tableColumnMap.get(tablename));
                    listSql.add(entityClass.create());
                }else{
                    listSql.addAll(entityClass.update(tableColumnMap.get(tablename)));
                }
            }

        }

        for (String s : listSql) {
            System.out.println("========================");
            System.out.println(s);
                        jdbcTemplate.update(s);
            System.out.println("---------------------------");

        }
        System.out.println("自动补全数据成功。。。");



    }

    private Resource[] getResourceFile(String dataName,String domainPackages) throws IOException {
        Map<String, List<String>> tablecolumn = getTableColumn(dataName);
        String basePackage = "classpath*:"+domainPackages.replaceAll("\\.","/")+"/*.class";
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        return resourcePatternResolver.getResources(basePackage);
    }

    /**
     * 通过jdbc.properties 配置文件找到数据库名
     * @param classpathFile
     * @param key
     * @return
     * @throws IOException
     */
    private String getDataName(String classpathFile,String key) throws IOException {
        String path = this.getClass().getClassLoader().getResource("/").getPath();
        String filepath = path + classpathFile;
        File file = new File(filepath);
        List<String> listline = FileUtils.readLines(file);
        String dataName = null;
        for (String s : listline) {
            if(StringUtils.isNotBlank(s)){
                if(!s.trim().startsWith("#")&&s.trim().contains("=")){

                    String[] ss = s.split("=");
                    if(key.equals(ss[0])){
                        dataName = ss[1].substring(ss[1].lastIndexOf("/")+1,ss[1].indexOf("?"));
                    }
                }

            }

        }
        return dataName;
    }

    /**
     * 通过数据库名找到 库中的table和column
     * @param dataName
     * @return Map<TABLE_NAME, List<String>> | TABLE_NAME,COLUMN_NAME
     */
    private Map<String, List<String>> getTableColumn(String dataName) {
        List<Map<String, Object>> listMap3 = jdbcTemplate.queryForList("select TABLE_NAME,COLUMN_NAME from information_schema.columns where table_schema='"+dataName+"'");

        Map<String, List<String>> tableName_ = new HashMap<String, List<String>>();
        List<String> columnList = null;
        for (Map<String, Object> stringObjectMap : listMap3) {
            columnList = tableName_.get(String.valueOf(stringObjectMap.get("TABLE_NAME")));
            if(columnList==null){
                columnList = new ArrayList<String>();
            }
            columnList.add(String.valueOf(stringObjectMap.get("COLUMN_NAME")));
            tableName_.put(String.valueOf(stringObjectMap.get("TABLE_NAME")),columnList);
        }
        return tableName_;
    }
    /**
     * 获取 数据库中 Table 名称
     * @param clazz
     * @param dbtable
     * @return
     */
    private String getTableName(Class<?> clazz, Table dbtable) {
        if(StringUtils.isNotBlank(dbtable.name())){
            return dbtable.name();
        }else{
            return clazz.getSimpleName().toLowerCase();
        }
    }
}
